/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ventanas;

import controlador.CtrlVista;
import excepciones.UsuarioException;
import java.security.NoSuchAlgorithmException;
import javax.swing.DefaultListModel;
import negocio.Complejo;
import negocio.Usuario;
import java.util.Iterator;
import java.util.Map;
import javax.swing.JOptionPane;

/**
 *
 * @author Diego
 */
public class FrmUser extends javax.swing.JDialog {
    private CtrlVista vista;// = new CtrlVista();
    private Usuario unUsuario;
    DefaultListModel modelUsuarios = new DefaultListModel();

    /**
     * Creates new form FrmUser
     */
    public FrmUser(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        try{
            this.vista = new CtrlVista();
        }
        catch(Exception e){            
            JOptionPane.showMessageDialog(this, "Error de Inicializacion");
        }
        this.inicializar();
    }   
    
    public void inicializar(){
        this.lstUsuarios.setModel(modelUsuarios);
        this.unUsuario = null;
        this.txtName.setText("");
        this.txtextado.setText("");
        this.txtnivel.setText("");
        this.txtpassword.setText("");
        this.txtName.setEnabled(false);
        this.txtextado.setEnabled(false);
        this.txtnivel.setEnabled(false);
        this.txtpassword.setEnabled(false);
        this.txtextado.setAction(null);
        this.btnBorrar.setEnabled(false);
        this.btnEditar.setEnabled(false);
        this.btnGuardar.setEnabled(false);
        this.btnNuevo.setEnabled(true);
        
        
        this.cargarUsuarios();
        
        
    }
    
    public void cargarUsuarios(){
        
        this.modelUsuarios.clear();
        this.lstUsuarios.setModel(modelUsuarios);
        if(this.vista.obtenerUsuarios().size() > 0){
            for(Map.Entry user : this.vista.obtenerUsuarios().entrySet()){                
                this.modelUsuarios.addElement((Usuario) user.getValue());
            }
        }else{
            this.modelUsuarios.addElement("No se Encontraron Usuarios");
        }
        
    }
    
    public void nuevoUsuario(){
        this.btnNuevo.setEnabled(false);
        this.btnGuardar.setEnabled(true);
        this.unUsuario = null;
        this.txtName.setText("");
        this.txtextado.setText("");
        this.txtnivel.setText("");
        this.txtpassword.setText("");
        this.txtName.setEnabled(true);
        this.txtextado.setEnabled(true);
        this.txtnivel.setEnabled(true);
        this.txtpassword.setEnabled(true);
        
    }
    
    public void guardarUsuario(){
        if(this.unUsuario == null){
            try{
                this.vista.agregarUsuario(this.txtName.getText(),this.txtpassword.getText(),this.txtnivel.getText());
                this.inicializar();
                JOptionPane.showMessageDialog(this, "Usuario cargado correctamente");
            }
            catch(Exception ex){
                JOptionPane.showMessageDialog(this, "Error al guardar Usuario"+ex.getMessage());
            }
        }else{
            
        }
    }
    
    public void seleccionarUsuario(){        
        if(this.modelUsuarios.size() > 0){
            this.unUsuario = (Usuario) this.modelUsuarios.getElementAt(this.lstUsuarios.getSelectedIndex());
            this.completarCampos();
            this.btnBorrar.setEnabled(true);
            this.btnEditar.setEnabled(true);
            this.btnNuevo.setEnabled(false);
            this.btnGuardar.setEnabled(true);
            
            this.txtName.setEnabled(true);
            this.txtextado.setEnabled(true);
            this.txtnivel.setEnabled(true);
            this.txtpassword.setEnabled(true);
        }
    }
    
    public void completarCampos(){
        if(this.unUsuario != null){
            this.txtName.setText(this.unUsuario.getUserName());
            //this.txtextado.setText(this.unUsuario.isEstado().toString);
            this.txtnivel.setText(this.unUsuario.getNivel());
            
        }
    }
    
    public void borrarUsuario(){
        
        if (this.unUsuario != null){
        //    this.vista.quitarUsuario(this.unUsuario.getUserName());
            this.unUsuario = null;
            this.txtName.setText("");
            this.txtName.setEnabled(false);
            this.txtextado.setText("");
            this.txtextado.setEnabled(false);
            this.txtnivel.setText("");
            this.txtnivel.setEnabled(false);
            this.txtpassword.setText("");
            this.txtpassword.setEnabled(false);
            this.btnBorrar.setEnabled(false);
            this.btnEditar.setEnabled(false);
            this.btnGuardar.setEnabled(false);
            this.btnNuevo.setEnabled(true);
            //this.modelUsuarios = null;
            //this.lstUsuarios.setModel(modelUsuarios);
            this.cargarUsuarios();
        }
        
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        lstUsuarios = new javax.swing.JList();
        btnNuevo = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnBorrar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        txtpassword = new javax.swing.JTextField();
        txtnivel = new javax.swing.JTextField();
        txtextado = new javax.swing.JTextField();
        btnGuardar = new javax.swing.JButton();
        btnAceptar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lstUsuarios.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        lstUsuarios.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lstUsuariosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(lstUsuarios);

        btnNuevo.setText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnEditar.setText("Editar");

        btnBorrar.setText("Borrar");
        btnBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBorrarActionPerformed(evt);
            }
        });

        jLabel1.setText("User Name");

        jLabel2.setText("Password");

        jLabel3.setText("Nivel");

        jLabel4.setText("Estado");

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnAceptar.setText("Aceptar");
        btnAceptar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnAceptarMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtName, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
                            .addComponent(txtpassword)
                            .addComponent(txtnivel)
                            .addComponent(txtextado))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnNuevo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnGuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEditar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnBorrar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnAceptar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 405, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(21, 21, 21)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(txtpassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(23, 23, 23)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(txtnivel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(31, 31, 31)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(txtextado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnNuevo)
                            .addComponent(btnEditar)
                            .addComponent(btnBorrar)
                            .addComponent(btnGuardar))
                        .addContainerGap(22, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnAceptar)
                        .addContainerGap())))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        // TODO add your handling code here:
        
        this.nuevoUsuario();
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
        this.guardarUsuario();
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void lstUsuariosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstUsuariosMouseClicked
        // TODO add your handling code here:
        
        /*
                if(this.modelVehiculos.size() > 0){
            this.unVehiculo = (Vehiculo) this.modelVehiculos.getElementAt(this.ListVehiculos.getSelectedIndex());
            this.completarCampos();
            this.BtnCancel.setEnabled(true);
            this.BtnEliminar.setEnabled(true);
            this.BtnNuevo.setEnabled(false);
        }
        
        */
        
        this.seleccionarUsuario();
    }//GEN-LAST:event_lstUsuariosMouseClicked

    private void btnBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBorrarActionPerformed
        // TODO add your handling code here:
        this.borrarUsuario();
    }//GEN-LAST:event_btnBorrarActionPerformed

    private void btnAceptarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAceptarMouseClicked
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnAceptarMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main2(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FrmUser dialog = new FrmUser(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnBorrar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList lstUsuarios;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtextado;
    private javax.swing.JTextField txtnivel;
    private javax.swing.JTextField txtpassword;
    // End of variables declaration//GEN-END:variables
}
